package com.cxj.musicplayer.musicsource.network;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;


public class DownloadFrom163 {

    private static String getRedirectUrl(String path) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) new URL(path)
                .openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setConnectTimeout(5000);
        return conn.getHeaderField("Location");
    }

    public static boolean download(Context context, String song_id){
        String path = context.getApplicationContext().getFilesDir().getAbsolutePath() + "/songs/";
        HttpURLConnection connection = null;
        System.out.println(path);
        try{
            String new_url = getRedirectUrl("http://music.163.com/song/media/outer/url?id=" + song_id + ".mp3");
            URL url = new URL(new_url);
            System.out.println(new_url);
            if(new_url.equals("http://music.163.com/404")){
                return false;
            }



            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(60000);
            connection.connect();
            System.out.println(connection.getResponseCode());
            if(connection.getResponseCode() == 200 || connection.getResponseCode() == 302){
                DataInputStream reader = new DataInputStream(connection.getInputStream());
                byte[] buffer = new byte[2048];
                File file = new File(path);
                if(!file.exists()){
                    file.mkdirs();
                }

                DataOutputStream writer = new DataOutputStream(new FileOutputStream(path + song_id + ".mp3"));
                int len = 0;
                while((len = reader.read(buffer)) != -1){
                    writer.write(buffer, 0, len);
                }

                reader.close();
                writer.close();
            }
            return true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return false;
    }

    private static String readFromUrl(String url) throws IOException {
        HttpURLConnection connection = null;
        URL u = new URL(url);
        connection = (HttpURLConnection) u.openConnection();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null){
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }

    public static String getPlayList() throws Exception {
        return readFromUrl("http://19991202.com/get_play_list");
    }

    public static String getTitleById(String id) throws IOException {
        return readFromUrl("http://19991202.com/get_title_by_id?id=" + id);
    }

    public static String getPicUrlById(String id) throws IOException {
        return readFromUrl("http://19991202.com/get_pic_by_id?id=" + id);
    }

    public static String[] getSongsByListId(String lid) throws IOException {
        return readFromUrl("http://19991202.com/get_song_by_list_id?lid=" + lid).split(" ");
    }

    public static Bitmap getHttpBitmap(String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setConnectTimeout(0);
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static void download_pic(String url, String pic_name){
        HttpURLConnection connection = null;
        try{
            Log.i(DownloadFrom163.class.getName() + ":pic_url::", url);
            URL u = new URL(url);
            System.out.println(url);
            connection = (HttpURLConnection) u.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(60000);
            connection.connect();
            System.out.println(connection.getResponseCode());
            if(connection.getResponseCode() == 200){
                DataInputStream reader = new DataInputStream(connection.getInputStream());
                byte[] buffer = new byte[1024 * 8];
                DataOutputStream writer = new DataOutputStream(new FileOutputStream(pic_name));
                int len = 0;
                while((len = reader.read(buffer)) != -1){
                    writer.write(buffer, 0, len);
                }

                reader.close();
                writer.close();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static String get_songname_and_author_name(String lid) throws IOException {
        return readFromUrl("http://19991202.com/get_song_by_list_id?lid=" + lid);
    }

    public static String get_song_pic_by_id(String id) throws IOException {
        return readFromUrl("http://19991202.com/get_song_pic_by_id?id=" + id);
    }



}
